<template>
  <el-dialog
    :title="titleMap[mode]"
    v-model="visible"
    width="40%"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <el-form
      :model="form"
      :rules="rules"
      :disabled="mode == 'show'"
      ref="dialogForm"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="头像" style="width: 100%">
        <sc-upload
          v-model="form.img"
          :limit="1"
          :showFileList="false"
          :headers="headers"
          :modelValue="form.img"
          title="上传头像"
        ></sc-upload>
      </el-form-item>
      <el-form-item label="登录账号" prop="account">
        <el-input
          v-model="form.account"
          placeholder="用于登录系统"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="账号类型" prop="accountType">
        <el-select
          v-model="form.accountType"
          filterable
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in accountType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入完整的真实姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="form.phone"
          placeholder="请输入正确的手机号"
          clearable
        ></el-input>
      </el-form-item>
      <template v-if="mode == 'add'">
        <el-form-item label="登录密码" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            clearable
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input
            type="password"
            v-model="form.password2"
            clearable
            show-password
          ></el-input>
        </el-form-item>
      </template>
      <el-form-item label="所属部门" prop="dept">
        <el-cascader
          v-model="form.dept"
          :options="depts"
          :props="deptsProps"
          clearable
          @change="selectDept"
          style="width: 100%"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="岗位" prop="positionId">
        <el-select v-model="form.positionId" clearable style="width: 100%">
          <el-option
            v-for="item in positionList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属角色" prop="roleId">
        <el-select
          v-model="form.roleId"
          filterable
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in groups"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch v-model="form.state" :inactive-value="2" :active-value="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        v-if="mode != 'show'"
        type="primary"
        :loading="isSaveing"
        @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
</template>

<script>
import sysConfig from "@/config"
import { verifyPhone } from '@/utils/verificate'
export default {
  emits: ['success', 'closed'],
  data () {
    return {
      headers: {},
      url: '/api/admin/upload',
      imageUrl: '',
      userId: '',//登录时的用户ID
      mode: "add",
      titleMap: {
        add: '新增用户',
        edit: '编辑用户',
        show: '查看'
      },
      visible: false,
      isSaveing: false,
      //表单数据
      form: {
        id: '',
        account: "",//账号
        departmentId: '',
        positionId: '',
        dept: [],
        img: "",//头像
        phone: "",
        roleId: '',
        role: [],
        state: 1,//账号状态 1启用2禁用
        username: "",
        password: '',
        password2: '',
        accountType: 2

      },
      accountType: [
        {
          value: 1,
          label: '管理员'
        },
        {
          value: 2,
          label: '普通用户'
        }
      ],
      //验证规则
      rules: {
        avatar: [
          { required: true, message: '请上传头像' }
        ],
        account: [
          { required: true, message: '请输入登录账号' }
        ],
        username: [
          { required: true, message: '请输入真实姓名' }
        ],
        phone: [
          { required: true, message: '请输入正确的手机号', trigger: 'blur' },
          { validator: verifyPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码' },
          {
            validator: (rule, value, callback) => {
              if (this.form.password2 !== '') {
                this.$refs.dialogForm.validateField('password2')
              }
              callback()
            }
          }
        ],
        password2: [
          { required: true, message: '请再次输入密码' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.form.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            }
          }
        ],
        dept: [
          { required: true, message: '请选择所属部门' }
        ],
        roleId: [
          { required: true, message: '请选择所属角色', trigger: 'change' }
        ],
        positionId: [
          { required: true, message: '请选择岗位', trigger: 'change' }
        ]

      },
      //所需数据选项
      groups: [],
      groupsProps: {
        value: "id",
        multiple: true,
        checkStrictly: true
      },
      depts: [],
      deptsProps: {
        value: "id",
        label: 'name',
        checkStrictly: true
      },
      positionList: [],
    }
  },
  beforeMount () {
    let token = this.$TOOL.cookie.get("TOKEN")
    this.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token
    let userInfo = this.$TOOL.data.get('USER_INFO')
    this.userId = userInfo.userId

  },
  mounted () {
    this.getGroup()
    this.getDept()
    this.getPositionList()
  },
  methods: {
    //显示
    open (mode = 'add') {
      this.mode = mode
      this.visible = true
      return this
    },
    //加载树数据  角色列表
    async getGroup () {
      var res = await this.$API.role.getRoleList.get()
      this.groups = res.data
    },
    // 获取部门列表
    async getDept () {
      var res = await this.$API.department.getDepartmentList.get()
      this.depts = res.data
    },

    // 选择部门
    selectDept () {
      this.form.positionId = ' '
      this.getPositionList()

    },
    // 获取岗位列表
    async getPositionList () {
      let { data } = await this.$API.position.getPositonList.get({ departmentId: this.form.dept[0] })
      this.positionList = data
      // managementState 1、直接主管，2普通员工,3、其他管理类岗位
      // this.form.positionId = ' '

      // if (this.form.dept[0] && this.mode != 'edit') {
      //   if (this.positionList.length == 0) {
      //     this.form.positionId = ' '
      //   } else {
      // this.positionList.map(item => {
      //   item.managementState && item.managementState == 2 ? this.form.positionId = item.id : this.form.positionId = ' '
      // })
      // }

      // }

    },
    //表单提交方法
    submit () {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true
          let res = null
          if (this.mode == 'add') {
            let data = {
              account: this.form.account,
              departmentId: this.form.dept[0],
              positionId: this.form.positionId,
              img: this.form.img,
              password: this.form.password,
              phone: this.form.phone,
              roleId: this.form.roleId,
              state: this.form.state,//账号状态 1启用2禁用
              username: this.form.username,
              accountType: this.form.accountType
            }
            res = await this.$API.user.addUser.post(data)
          } else if (this.mode == 'edit') {
            let data = {
              id: this.form.id,
              account: this.form.account,
              departmentId: this.form.dept[0],
              positionId: this.form.positionId,
              img: this.form.img,
              phone: this.form.phone,
              roleId: this.form.roleId,
              state: this.form.state,//账号状态 1启用2禁用
              username: this.form.username,
              accountType: this.form.accountType
            }
            res = await this.$API.user.updateUserInfo.post(data)
          }

          this.isSaveing = false
          if (res.code == 200) {
            this.$emit('success', this.form, this.mode)
            this.visible = false
            this.$message.success("操作成功")
          }
        } else {
          return false
        }
      })
    },
    //表单注入数据
    setData (data) {
      console.log(data)
      // this.form.id = data.id
      this.form.id = data.id
      this.form.account = data.account
      this.form.img = data.img
      this.form.username = data.username
      this.form.phone = data.phone
      // this.form.role[0] = data.roleId
      this.form.roleId = data.roleId
      this.form.dept[0] = data.departmentId
      this.form.departmentId = data.departmentId
      this.form.accountType = data.accountType
      this.form.positionId = data.positionId
      this.getPositionList()
    },

  }
}
</script>

<style scoped>
</style>
